package cn.itsource.ymcc.mqlistener;

import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.dto.PayOrderDataDto;
import cn.itsource.ymcc.service.ICourseOrderService;
import cn.itsource.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.nio.charset.StandardCharsets;

//事务监听器
@RocketMQTransactionListener(txProducerGroup = "PayMesGroup")
public class PayMesListener implements RocketMQLocalTransactionListener {
    /**
     * 保存订单
     * @param message
     * @param o
     * @return
     */
    @Autowired
    private ICourseOrderService courseOrderService;
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object o) {
        try {
            AssertUtil.isNotNull(o,"order信息为空");
            CourseOrder order = (CourseOrder) o;
            //保存订单
            courseOrderService.saveOrderAndItem(order);

            //保存支付订单


            return RocketMQLocalTransactionState.COMMIT;

        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;
        }
    }

    /**
     * 检查订单是否保存成功
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        try {
            AssertUtil.isNotNull(message,"message信息为空");
            //会变成byte【】
            byte[] msg = (byte[])message.getPayload();
            String s = new String(msg, StandardCharsets.UTF_8);
            PayOrderDataDto dto = JSON.parseObject(s, PayOrderDataDto.class);
            //拿订单号
            String orderNo = dto.getOrderNo();
            //查询是否保存成功
            CourseOrder courseOrder = courseOrderService.selectByOrderNo(orderNo);

            return courseOrder == null ? RocketMQLocalTransactionState.ROLLBACK : RocketMQLocalTransactionState.COMMIT;

        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.UNKNOWN;
        }
    }
}
